package giftmail.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.wuwz.poi.ExcelKit;
import org.wuwz.poi.ExcelType;
import org.wuwz.poi.OnReadDataHandler;

import giftmail.dao.ExcelDb;
import giftmail.model.UserExcel;

@Controller
@RequestMapping(value = "/example")
public class UserExcelController {

	/**
	 * 通过浏览器导出Excel文件
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/export", method = { RequestMethod.GET })
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		//去掉此段创建数据的代码  ==》  增加了在dao层中的UserExcel.java，模拟增加数据的方法
//		List<UserExcel> users = Lists.newArrayList();
//		for (int i = 0; i < 300; i++) {
//			UserExcel e = new UserExcel();
//			e.setUid(i + 1);
//			e.setUsername("USERNAME_" + (i + 1));
//			e.setPassword("asdasdasdasd");
//			e.setNickname("NICKNAME_" + (i + 1));
//			e.setAge(18);
//			users.add(e);
//		}
		
		// 生成Excel并使用浏览器下载
//		ExcelKit.$Export(UserExcel.class, response).toExcel(users, "用户信息");
		
		// 生成Excel并使用浏览器下载()  ==》  增加了在dao层中的UserExcel.java，模拟增加数据的方法
		ExcelKit.$Export(UserExcel.class, response).toExcel(ExcelDb.getUsers(), "用户信息");
	}
	
	/**
	 * 生成模板文件
	 * @param response
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/muban", method = { RequestMethod.GET })
	private void downTemplFile(HttpServletResponse response) throws FileNotFoundException, IOException {
		File tmplFile = new File(String.format("%s/import_template.xlsx", System.getProperty("java.io.tmpdir")));
		
		if(!tmplFile.exists()) {
			// 构建模版文件
			ExcelKit.$Builder(UserExcel.class).toExcel(null, "用户信息", new FileOutputStream(tmplFile));
		}

		// 执行下载
		@SuppressWarnings("deprecation")
		String fileName = URLEncoder.encode(tmplFile.getName());
		response.reset();
		response.setContentType(ExcelKit.$Import().getContentType(ExcelType.EXCEL2007));
		response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

		int fileLength = (int) tmplFile.length();
		response.setContentLength(fileLength);
		if (fileLength != 0) {
			InputStream inStream = new FileInputStream(tmplFile);
			byte[] buf = new byte[4096];
			ServletOutputStream servletOS = response.getOutputStream();
			int readLength;
			while (((readLength = inStream.read(buf)) != -1)) {
				servletOS.write(buf, 0, readLength);
			}
			inStream.close();
			servletOS.flush();
			servletOS.close();
		}
	}

	/**
	 * Excel文件导入
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/importExcel", method = { RequestMethod.POST })
	private void importExcelFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter writer = response.getWriter();
		if (!ServletFileUpload.isMultipartContent(request)) {
		    writer.println("Error: 表单必须包含 enctype=multipart/form-data");
		    writer.flush();
		    return;
		}
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
		factory.setSizeThreshold(1024 * 1024 * 3);
		// 设置临时存储目录
		factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置最大文件上传值
		upload.setFileSizeMax(1024 * 1024 * 40);
		// 设置最大请求值 (包含文件和表单数据)
		upload.setSizeMax(1024 * 1024 * 50);
 
		// 构造临时路径来存储上传的文件
		String uploadPath = request.getServletContext().getRealPath("./") + File.separator + "upload";
		File uploadDir = new File(uploadPath);
		if (!uploadDir.exists()) {
		    uploadDir.mkdir();
		}
 
		try {
		    // 解析请求的内容提取文件数据
		    List<FileItem> formItems = upload.parseRequest(request);
 
		    if (formItems != null && formItems.size() > 0) {
		        for (FileItem item : formItems) {
		            if (!item.isFormField()) {
		                String fileName = new File(item.getName()).getName();
		                String filePath = uploadPath + File.separator + fileName;
		                File storeFile = new File(filePath);
		                System.out.println(filePath);
		                item.write(storeFile);
		                
		                //=============开始解析Excel文件并入库=================
		                ExcelKit.$Import().readExcel(storeFile, new OnReadDataHandler() {
							
							@Override
							public void handler(List<String> rowData) {
								UserExcel user = new UserExcel();
								user.setUid(Integer.parseInt(rowData.get(0)));
								user.setUsername(rowData.get(1));
								user.setPassword(rowData.get(2));
								user.setNickname(rowData.get(3));
								user.setAge(18);
								ExcelDb.addUser(user);
							}
						});
		                
		                if(storeFile.exists()) {
		                	storeFile.delete();
		                }
		                // 跳转列表页
		                toListPage(request, response);
		            }
		        }
		    }
		} catch (Exception ex) {
			writer.println("Error: "+ex.getMessage());
			writer.flush();
		}
	}
	
	/**
	 * 查看数据列表
	 * 对应list.jsp
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/list", method = { RequestMethod.GET })
	private void toListPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setAttribute("users", ExcelDb.getUsers());
		request.getRequestDispatcher("/list.jsp").forward(request, response);
	}
}
